package com.nervenets.general.interceptor;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.nervenets.general.jwt.util.JwtUtils;
import com.nervenets.general.wapper.NerveNetsHttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Map;

@Slf4j
public class WebInvokeTimeInterceptor implements HandlerInterceptor {
    private final InheritableThreadLocal<StopWatch> invokeTimeTL = new InheritableThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StopWatch stopWatch = new StopWatch();
        invokeTimeTL.set(stopWatch);
        stopWatch.start();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        StopWatch stopWatch = invokeTimeTL.get();
        if (null == stopWatch) return;
        stopWatch.stop();
        String loginUserNameElseNull = JwtUtils.getUserNameOrNull();
        String url = (null == loginUserNameElseNull ? "" : (loginUserNameElseNull + " ")) + request.getMethod() + " " + request.getRequestURI() + " " + response.getStatus();
        // 打印请求参数
        if (isJsonRequest(request) && !"GET".equalsIgnoreCase(request.getMethod())) {
            String jsonParam = "";
            if (request instanceof NerveNetsHttpServletRequestWrapper) {
                BufferedReader reader = request.getReader();
                jsonParam = IoUtil.read(reader);
            }
            log.info("{} {}, 参数类型[json] {} 耗时{}:{}ms", ServletUtil.getClientIP(request), url, jsonParam, stopWatch.getTime() > 500 ? "太长" : "", stopWatch.getTime());
        } else {
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (MapUtil.isNotEmpty(parameterMap)) {
                String parameters = JSON.toJSONString(parameterMap);
                log.info("{} {}, 参数类型[param] {} 耗时{}:{}ms", ServletUtil.getClientIP(request), url, parameters, stopWatch.getTime() > 500 ? "太长" : "", stopWatch.getTime());
            } else {
                log.info("{} {}, 无参, 耗时{}:{}ms", ServletUtil.getClientIP(request), url, stopWatch.getTime() > 500 ? "太长" : "", stopWatch.getTime());
            }
        }
        invokeTimeTL.remove();
    }

    /**
     * 判断本次请求的数据类型是否为json
     *
     * @param request request
     * @return boolean
     */
    private boolean isJsonRequest(HttpServletRequest request) {
        String contentType = request.getContentType();
        if (contentType != null) {
            return StringUtils.startsWithIgnoreCase(contentType, MediaType.APPLICATION_JSON_VALUE);
        }
        return false;
    }

}
